package org.gwu.seuss;

import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.gwu.seuss.communication.crypto.CryptoUtil;
import org.gwu.seuss.communication.sockets.ssl.Util;
import org.gwu.seuss.communication.util.PasswordPrompt;
import org.gwu.seuss.server.SeussServer;
import org.gwu.seuss.server.SeussServerFactory;
import org.gwu.seuss.service.ServiceFactory;

public class App {
	private static final String CONNECTION_PROPERTIES = "connection.properties";
	private static final String SSL_PORT = "ssl.port";
	static Logger log = Logger.getLogger(App.class);

	public static void main(String[] args) {

		SeussServer ss = null;
		char[] sslStorePassword = null;
		char[] systemAdminPassword = null;

		try {
		
			Properties connectionProps = Util.loadPropertiesFromResource(CONNECTION_PROPERTIES);
			sslStorePassword = PasswordPrompt.askForPassword("Please enter SSL store password");
			systemAdminPassword = PasswordPrompt.askForPassword("Please enter server admin password");
			
			CryptoUtil.getInstance().createKeyStore(String.valueOf(systemAdminPassword));
			
			ss = SeussServerFactory.createSslServer(sslStorePassword, Integer.parseInt(connectionProps.getProperty(SSL_PORT)));
		
		} catch (Exception ex) {
			log.error("Failed to create ssl server", ex);
		} finally {

			if (sslStorePassword != null) {
				Arrays.fill(sslStorePassword, ' ');
			}
			if (systemAdminPassword != null) {
				Arrays.fill(systemAdminPassword, ' ');
			}
			
		}

		try {
			ServiceFactory.initDataBaseService();
		} catch (Exception ex) {
			log.error("Failed to initialize database service", ex);
		}

		if (ss != null) {

			log.info("Starting seuss server. Listening on port " + ss.getPort());

			try {
				ss.start();
			} catch (IOException e) {
				log.error("Failed to startup the Seuss Server", e);
			}
		}
	}
}
